package server;

import server.pojo.Notice;
import server.pojo.PassState;
import server.pojo.Teacher;
import server.utils.IDUtils;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Objects;

public class GUI {
	static class Login {
		public Login(JFrame frame) {
			frame.getContentPane().removeAll();
			JPanel panel = new JPanel();
			frame.add(panel, BorderLayout.NORTH);
			panel.setBorder(new EmptyBorder(20, 20, 20, 20));
			panel.setLayout(new GridLayout(2, 2, 10, 10));
			panel.add(new JLabel("ID:"));
			JTextField name = new JTextField();
			panel.add(name);
			panel.add(new JLabel("Password:"));
			JPasswordField pswd = new JPasswordField();
			panel.add(pswd);

			JPanel panel1 = new JPanel();
			frame.add(panel1, BorderLayout.SOUTH);
			panel1.setLayout(new FlowLayout());
			JButton login = new JButton("login");
			panel1.add(login);
			login.getRootPane().setDefaultButton(login);

			JButton register = new JButton("register");
			panel1.add(register);
			panel1.setBorder(new EmptyBorder(20, 20, 20, 20));

			login.addActionListener(e -> {
				try {
					var t = Handler.login(Long.parseLong(name.getText()), String.valueOf(pswd.getPassword()));
					new MainApp(frame, t);
				} catch (Exception ex) {
					JOptionPane.showMessageDialog(frame, ex.getMessage(), "登录错误", JOptionPane.PLAIN_MESSAGE);
				}
			});
			register.addActionListener(e -> {
				new Register(frame);
			});
			frame.setSize(300, 200);
			frame.setVisible(true);
			Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
			frame.setLocation((size.width - frame.getSize().width) / 2, (size.height - frame.getSize().height) / 2);
		}
	}

	static class Register {
		public Register(JFrame frame) {
			frame.getContentPane().removeAll();

			JPanel panel = new JPanel();
			frame.add(panel, BorderLayout.NORTH);
			panel.setBorder(new EmptyBorder(20, 20, 20, 20));
			panel.setLayout(new GridLayout(7, 2, 10, 10));

			panel.add(new JLabel("Type:"));
			JRadioButton xb = new JRadioButton("辅导员");
			JRadioButton yb = new JRadioButton("院长");
			ButtonGroup group = new ButtonGroup();
			group.add(xb);
			group.add(yb);
			JPanel tmp = new JPanel();
			tmp.add(xb);
			tmp.add(yb);
			panel.add(tmp);

			panel.add(new JLabel("ID:"));
			JTextField id = new JTextField();
			panel.add(id);

			panel.add(new JLabel("Password:"));
			JPasswordField pswd = new JPasswordField();
			panel.add(pswd);

			panel.add(new JLabel("Name:"));
			JTextField name = new JTextField();
			panel.add(name);

			panel.add(new JLabel("Sex:"));
			JTextField sex = new JTextField();
			panel.add(sex);

			panel.add(new JLabel("Department ID:"));
			JTextField depart = new JTextField();
			panel.add(depart);

			panel.add(new JLabel("Grade:"));
			JTextField grade = new JTextField();
			panel.add(grade);

			JPanel panel1 = new JPanel();
			frame.add(panel1, BorderLayout.SOUTH);
			panel1.setLayout(new FlowLayout());
			JButton login = new JButton("login");
			panel1.add(login);
			JButton register = new JButton("register");
			panel1.add(register);
			panel1.setBorder(new EmptyBorder(20, 20, 20, 20));

			xb.addActionListener(e -> {
				grade.setEditable(true);
			});
			yb.addActionListener(e -> {
				grade.setEditable(false);
			});
			login.addActionListener(e -> {
				new Login(frame);
			});
			register.addActionListener(e -> {
				try {
					HashMap<String, String> a = new HashMap<>();
					a.put("id", id.getText());
					a.put("name", name.getText());
					a.put("sex", sex.getText());
					a.put("grade", xb.isSelected() ? grade.getText() : "0");
					a.put("pswd", String.valueOf(pswd.getPassword()));
					a.put("t", xb.isSelected() ? "1" : "2");
					a.put("depart_id", depart.getText());
					for (var i : a.values()) {
						if (i == null || Objects.equals(i, "")) {
							JOptionPane.showMessageDialog(frame, "信息不能留空", "注册错误", JOptionPane.PLAIN_MESSAGE);
							return;
						}
					}
					Handler.register(a);
					new Login(frame);
				} catch (Exception ex) {
					JOptionPane.showMessageDialog(frame, ex.getMessage(), "登录错误", JOptionPane.PLAIN_MESSAGE);
				}
			});
			frame.pack();
			frame.setVisible(true);
			Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
			frame.setLocation((size.width - frame.getSize().width) / 2, (size.height - frame.getSize().height) / 2);

		}
	}

	static class MainApp {
		Handler handler;

		public MainApp(JFrame frame, Teacher t) {
			handler = new Handler(t);
			frame.getContentPane().removeAll();

			JPanel panel1 = new JPanel();
			frame.add(panel1, BorderLayout.NORTH);
			panel1.setLayout(new FlowLayout(FlowLayout.RIGHT));
			panel1.setBorder(new EmptyBorder(20, 20, 20, 20));

			JButton account = new JButton("账户信息");
			panel1.add(account);

			JButton notice = new JButton("公告");
			panel1.add(notice);

			JPanel panel2 = new JPanel();
			frame.add(panel2, BorderLayout.CENTER);
			panel2.setLayout(new FlowLayout(FlowLayout.RIGHT));
			JButton flush = new JButton("刷新"),
					pass = new JButton("批准"),
					nopass = new JButton("不批准");
			panel2.add(flush);
			panel2.add(pass);
			panel2.add(nopass);
			panel2.setBorder(new EmptyBorder(20, 20, 20, 20));

			var model = new DefaultTableModel();
			String[] columnNames = {
					"apply_id",
					"out_time",
					"back_time",
					"place",
					"tip",
					"student_id",
					"student_name",
					"stat",
					"comment"
			};
			model.setColumnIdentifiers(columnNames);

			JTable table = new JTable(model);
			table.setAutoCreateRowSorter(true);
			frame.add(new JScrollPane(table), BorderLayout.SOUTH);

			account.addActionListener(e -> {
				var dialog = new JDialog(frame);//dialog
				new Account(dialog);
			});

			flush.addActionListener(e -> {
				var list = handler.selectItem();
				String[][] rows = new String[list.size()][];
				int cnt = 0;
				for (var i : list) {
					rows[cnt] = new String[]{
							i.apply_id.toString(),
							i.out_time.toString(),
							i.back_time.toString(),
							i.place.toString(),
							i.tip.toString(),
							Long.toString(i.student_id),
							i.student_name.toString(),
							i.stat.toString(),
							i.recom.toString()
					};
					++cnt;
				}
				model.setDataVector(rows, columnNames);
			});
			pass.addActionListener(e -> {
				if (handler.getT().t == 1) {
					for (int i : table.getSelectedRows()) {
						String apply_id = (String) model.getValueAt(table.convertColumnIndexToModel(i), 0);
						handler.updateItem(PassState.UNDECIDED2, apply_id);
						model.setValueAt(PassState.UNDECIDED2.toString(), i, 7);
					}
				} else {
					for (int i : table.getSelectedRows()) {
						String apply_id = (String) model.getValueAt(table.convertColumnIndexToModel(i), 0);
						handler.updateItem(PassState.PASS, apply_id);
						model.setValueAt(PassState.PASS.toString(), i, 7);
					}
				}
			});
			nopass.addActionListener(e -> {
				String recom = JOptionPane.showInputDialog(frame, "", "不通过理由\n", JOptionPane.PLAIN_MESSAGE);
				if (handler.getT().t == 1) {
					for (int i : table.getSelectedRows()) {
						String apply_id = (String) model.getValueAt(table.convertColumnIndexToModel(i), 0);
						handler.updateItem(PassState.NOPASS1, apply_id);
						model.setValueAt(PassState.NOPASS1.toString(), i, 7);
						model.setValueAt(recom, i, 8);
					}
				} else {
					for (int i : table.getSelectedRows()) {
						String apply_id = (String) model.getValueAt(table.convertColumnIndexToModel(i), 0);
						handler.updateItem(PassState.NOPASS2, apply_id);
						model.setValueAt(PassState.NOPASS2.toString(), i, 7);
						model.setValueAt(recom, i, 8);
					}
				}
			});
			notice.addActionListener(e -> {
				var dialog = new JDialog(frame);//dialog
				new NoticeDialog(dialog);
			});

			flush.doClick();
			frame.setSize(800, 600);
			frame.setVisible(true);
			Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
			frame.setLocation((size.width - frame.getSize().width) / 2, (size.height - frame.getSize().height) / 2);
		}

		class Account { //as MainApp internal class to get its handler

			public Account(JDialog dialog) {
				dialog.getContentPane().removeAll();

				JPanel panel = new JPanel();
				dialog.add(panel, BorderLayout.NORTH);
				panel.setBorder(new EmptyBorder(20, 20, 20, 20));
				panel.setLayout(new GridLayout(7, 2, 10, 10));

				panel.add(new JLabel("ID:"));
				JTextField id = new JTextField(Long.toString(handler.getT().id));
				id.setEditable(false);
				panel.add(id);

				panel.add(new JLabel("Password:"));
				JPasswordField pswd = new JPasswordField(handler.getT().pswd);
				panel.add(pswd);

				panel.add(new JLabel("Name:"));
				JTextField name = new JTextField(handler.getT().name);
				panel.add(name);

				panel.add(new JLabel("Sex:"));
				JTextField sex = new JTextField(handler.getT().sex);
				panel.add(sex);

				panel.add(new JLabel("Grade:"));
				JTextField grade = new JTextField(Integer.toString(handler.getT().grade));
				panel.add(grade);

				panel.add(new JLabel("Type:"));
				JRadioButton xb = new JRadioButton("辅导员");
				JRadioButton yb = new JRadioButton("院长");
				ButtonGroup group = new ButtonGroup();
				group.add(xb);
				group.add(yb);
				if (handler.getT().t == 1)
					xb.setSelected(true);
				else
					yb.setSelected(true);
				JPanel tmp = new JPanel();
				tmp.add(xb);
				tmp.add(yb);
				panel.add(tmp);

				panel.add(new JLabel("Department ID:"));
				JTextField depart = new JTextField(Long.toString(handler.getT().depart_id));
				panel.add(depart);

				JPanel panel1 = new JPanel();
				dialog.add(panel1, BorderLayout.SOUTH);
				panel1.setLayout(new FlowLayout());
				JButton update = new JButton("更新");
				panel1.add(update);
				JButton delete = new JButton("删号");
				panel1.add(delete);
				panel1.setBorder(new EmptyBorder(20, 20, 20, 20));

				delete.addActionListener(e -> {
					int op = JOptionPane.showConfirmDialog(dialog, "是否彻底删除此账户？", "删号确认", JOptionPane.OK_CANCEL_OPTION);
					if (op == 0) {
						handler.delete();
					}
				});
				update.addActionListener(e -> {
					HashMap<String, String> a = new HashMap<>();
					a.put("id", id.getText());
					a.put("name", name.getText());
					a.put("sex", sex.getText());
					a.put("grade", xb.isSelected() ? grade.getText() : "0");
					a.put("pswd", String.valueOf(pswd.getPassword()));
					a.put("depart_id", String.valueOf(depart.getText()));
					a.put("t", xb.isSelected() ? "1" : "2");
					handler.update(a);
				});
				dialog.pack();
				dialog.setVisible(true);
				Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
				dialog.setLocation((size.width - dialog.getSize().width) / 2, (size.height - dialog.getSize().height) / 2);
			}
		}

		class NoticeDialog {
			public NoticeDialog(JDialog dialog) {
				dialog.getContentPane().removeAll();

				JPanel panel = new JPanel();
				dialog.add(panel, BorderLayout.NORTH);

				JButton ins = new JButton("发布新公告");
				JButton flush = new JButton("刷新");
				panel.add(flush);
				panel.add(ins);

				var model = new DefaultTableModel();
				String[] columnNames = {
						"标题",
						"内容",
						"发布者",
						"学院ID"
				};
				model.setColumnIdentifiers(columnNames);

				JTable table = new JTable(model);
				table.setAutoCreateRowSorter(true);
				dialog.add(new JScrollPane(table), BorderLayout.SOUTH);

				flush.addActionListener(e -> {
					var list = handler.selectNotice();
					String[][] rows = new String[list.size()][];
					int cnt = 0;
					for (var i : list) {
						rows[cnt] = new String[]{
								i.title,
								i.text,
								i.teacher_name,
								String.valueOf(i.depart_id)
						};
						++cnt;
					}
					model.setDataVector(rows, columnNames);
				});
				ins.addActionListener(e -> {
					String title = JOptionPane.showInputDialog(dialog, "", "标题：\n", JOptionPane.PLAIN_MESSAGE);
					if (title == null) return;
					String text = JOptionPane.showInputDialog(dialog, "", "正文：\n", JOptionPane.PLAIN_MESSAGE);
					if (text == null) return;
					Notice x = new Notice(
							IDUtils.getId(),
							title,
							text,
							handler.getT().id,
							handler.getT().name,
							handler.getT().t,
							handler.getT().depart_id);
					handler.insertNotice(x);
				});
				flush.doClick();
				dialog.pack();
				dialog.setVisible(true);
				Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
				dialog.setLocation((size.width - dialog.getSize().width) / 2, (size.height - dialog.getSize().height) / 2);
			}
		}
	}
}
